/**
 * 
 */
package com.sf.osms.dep.quartz;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.sf.novatar.cluster.IKeepAliveAndLockResolver;
import com.sf.osms.dep.biz.ICommonServiceBiz;
import com.sf.osms.dep.biz.IHandoverBiz;
import com.sf.osms.dep.biz.IRouterBiz;
import com.sf.osms.dep.biz.IRouterTmpBiz;
import com.sf.osms.dep.cache.SysConfigCacheHelper;
import com.sf.osms.dep.domain.Handover;
import com.sf.osms.dep.domain.Router;
import com.sf.osms.dep.domain.RouterTmp;
import com.sf.osms.dep.processor.exception.RouterException;
import com.sf.osms.dep.processor.util.RouterConstants;
import com.sf.osms.dep.processor.util.VerifyRouter;

/**
 * @author sfhq1469
 * DEP路由节点定时任务
 */
public class HandoverMatchJob {
	
	private static Logger logger = LoggerFactory.getLogger(HandoverMatchJob.class);
	
	public static final String LOCK_NAME = "handover_lock";
	
	@Autowired
	private IHandoverBiz handoverBiz;
	
	@Autowired
	private IRouterTmpBiz routerTmpBiz;
	
	
	@Autowired
	private IRouterBiz routerBiz;
	
	@Autowired
	private  IKeepAliveAndLockResolver clusterSync;
	
	@Autowired
	private ICommonServiceBiz commonService;
	
	/***
     * 路由节点定时任务
     */
	public void job()
	{ 
		logger.info("------------>HandoverMatchJob enter job method");
		if(clusterSync.isLockedFor(LOCK_NAME)){
			return;
		}
		boolean lock = clusterSync.getLockFor(LOCK_NAME);
		if(!lock){
			return;
		} 
		logger.info("------------>HandoverMatchJob start");

		try {
			match();
		} catch (Exception e) { 
			logger.error("------------>handover match error!"+e.getMessage()); 
		} 	
		clusterSync.releaseLockFor(LOCK_NAME);  
		
		logger.info("------------>HandoverMatchJob End");
	}  
	
	
	
	public void match(){
		Integer days  = Integer.valueOf(SysConfigCacheHelper.getSysConfigValue("handover_match_days"));		
		if (null == days) {
			logger.error("HANDOVER_MATCH_DAYS No configuration");
			days = 10;
		}
		
		logger.info("handover_match_days:" +days);
		Date startDate = new Date(Long.valueOf(new Date().getTime() - days*24*60*60*1000));
		
		logger.info("match 时间范围是："+days+"天前至今");

		List<Handover> handoverList = handoverBiz.queryWithinTime(startDate);

		Handover handover;
		RouterTmp routerTmp;
		Router router;
		boolean handleOK = true;
		List<RouterTmp> routerTmpList;
		for (int i = 0; i < handoverList.size(); i++) {
			handover = handoverList.get(i);
			routerTmpList = routerTmpBiz.queryWithinTime(startDate,
					handover.getAgentWaybill());
			// 没有找到相关的数据
			if (CollectionUtils.isEmpty(routerTmpList)) {
				continue;
			}

			// 找到相关数据
			for (int j = 0; j < routerTmpList.size(); j++) {
				routerTmp = routerTmpList.get(j);
				routerTmp.setSfWaybill(handover.getSfWaybill());
				router = new Router();
				BeanUtils.copyProperties(routerTmp, router);
				router.setId(null);
				router.setFailReason(null);
				//入库：
				saveRouter(router,routerTmp,handover);
			}
			handover.setStatus("M");
			handover.setMatchDate(new Date());
			handoverBiz.saveOrUpdate(handover);
		
	}
}
	
	
	
	public void saveRouter(Router router, RouterTmp routerTmp, Handover handover) {
		try {
			//1.常规校验
			VerifyRouter.commonVertify(router);
			//校验成功更改状态：
			router.setStatus(2);
			routerTmp.setFailReason(null);
			
		}catch (RouterException e) {
			logger.error("校验失败", e);
			router.setStatus(1);
			router.setFailReason(e.getExceptionCode());
			routerTmp.setFailReason(e.getExceptionCode());
		}
		
		try {
			//2.重复性校验
			List<Router> existRouter = commonService.findRouterInfo(
					router.getSfWaybill(), router.getEventCode(), false);
			//2.1正确数据，重复：不管
			if (CollectionUtils.isNotEmpty(existRouter)) {
				routerTmp.setFailReason("correct records exists already");
				routerTmp.setMatchTime(new Date());
				routerTmpBiz.saveOrUpdate(routerTmp);
				return;
				// 更改状态
			}

			//2.2错误数据,删除旧数据
			List<Router> errorRouter = commonService.findRouterInfo(
					router.getSfWaybill(), router.getEventCode(), true);
			if (CollectionUtils.isNotEmpty(errorRouter)) {
				// 删除重复
				commonService.removeRouterBatch(errorRouter);				
			}
			
			//3.暂时还没入库的，新增
			// 更新router
			
			//V2.4 将巴枪设备号替换
			router.setBarSn(RouterConstants.HANDOVER_BAR_SN);			
			routerBiz.save(router);
			// 更新tmp
			routerTmp.setMatchTime(new Date());
			routerTmpBiz.saveOrUpdate(routerTmp);
			
		} catch (Exception e) {
			logger.error("handover match 错误", e.getMessage());
		}

	}
	


	
	
	
	
	
	
}
